/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.academy.service.impl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ar.uba.fi.posgrado.academy.dao.TeacherDAO;
import ar.uba.fi.posgrado.academy.model.Body;
import ar.uba.fi.posgrado.academy.model.Teacher;
import ar.uba.fi.posgrado.academy.service.TeacherService;
import ar.uba.fi.posgrado.common.dao.DAOException;
import ar.uba.fi.posgrado.common.dao.NoSuchEntityException;
import ar.uba.fi.posgrado.common.exception.MissingArgumentException;
import ar.uba.fi.posgrado.common.exception.PosgradoException;
import ar.uba.fi.posgrado.common.exception.PosgradoRuntimeException;
import ar.uba.fi.posgrado.common.exception.RepeatedInstanceException;
import ar.uba.fi.posgrado.common.exception.RepeatedNameException;
import ar.uba.fi.posgrado.common.model.User;
import ar.uba.fi.posgrado.common.util.CriterionBuilder;
import ar.uba.fi.posgrado.common.util.ExpressionOperator;
import ar.uba.fi.posgrado.economy.model.ProviderAccount;
import ar.uba.fi.posgrado.economy.service.ProviderAccountService;

public class TeacherServiceImpl implements TeacherService {

	/** Logger */
	private static Logger logger = Logger.getLogger(TeacherServiceImpl.class);

	private TeacherDAO teacherDAO;
	
	private ProviderAccountService providerAccountService;

	public TeacherDAO getTeacherDAO() {
		return teacherDAO;
	}

	public void setTeacherDAO(TeacherDAO teacherDAO) {
		this.teacherDAO = teacherDAO;
	}
	
	/**
	 * @return the providerAccountService
	 */
	public ProviderAccountService getProviderAccountService() {
		return providerAccountService;
	}

	/**
	 * @param providerAccountService
	 *            the providerAccountService to set
	 */
	public void setProviderAccountService(
			ProviderAccountService providerAccountService) {
		this.providerAccountService = providerAccountService;
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void create(Teacher teacher) throws MissingArgumentException,
			PosgradoException {
		if (StringUtils.isBlank(teacher.getFileNumber())
				|| StringUtils.isBlank(teacher.getName())
				|| StringUtils.isBlank(teacher.getCv())
				|| StringUtils.isBlank(teacher.getDegree())
				|| StringUtils.isBlank(teacher.getPersonalId())
				|| StringUtils.isBlank(teacher.getTaxId())
				|| teacher.getBody() == null) {
			String mensaje = "El legajo, el nombre y el ente son datos obligatorios para guardar un docente. "
					+ "Tambien debe ingresar el curriculum, el titulo, el numero de documento y el CUIT/CUIL";
			throw new MissingArgumentException(mensaje);
		}

		try {
			this.getTeacherDAO().getByFileNumber(teacher.getFileNumber());
			throw new RepeatedInstanceException(
					"Ya existe o existio un docente con el legajo "
							+ teacher.getFileNumber());
		} catch (NoSuchEntityException e) {
			// si no encuentra el docente, se puede crear (no existe ninguno con
			// ese legajo)
		}
		ProviderAccount account = newAccountFromTeacher(teacher);
		// crea la cuenta corriente asociada
		this.getProviderAccountService().create(account);
		teacher.setAccount(account);
		// crea el docente en la base de datos
		this.getTeacherDAO().save(teacher); // usa el dao para crear el objeto
	}

	private ProviderAccount newAccountFromTeacher(Teacher teacher) {
		ProviderAccount account = new ProviderAccount();
		account.setProvider(teacher);
		account.setTotalDebt(0d);
		return account;
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void delete(Teacher t) throws PosgradoRuntimeException,
			PosgradoException {
		this.getTeacherDAO().remove(t);
	}

	@Transactional(readOnly = true)
	public List<Teacher> getAll() throws PosgradoRuntimeException,
			PosgradoException {
		return this.getTeacherDAO().findAll();
	}

	@Transactional(readOnly = true)
	public Teacher getById(Long id) throws PosgradoRuntimeException,
			PosgradoException {
		return (Teacher) this.getTeacherDAO().findById(id);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public Teacher update(Teacher teacher) throws PosgradoRuntimeException,
			PosgradoException {
		Teacher toUpdateTeacher = this.getById(teacher.getId());

		if (StringUtils.isBlank(teacher.getFileNumber())
				|| StringUtils.isBlank(teacher.getName())
				|| StringUtils.isBlank(teacher.getCv())
				|| StringUtils.isBlank(teacher.getDegree())
				|| StringUtils.isBlank(teacher.getPersonalId())
				|| StringUtils.isBlank(teacher.getTaxId())
				|| teacher.getBody() == null) {
			String mensaje = "El legajo, el nombre y el ente son datos obligatorios para guardar un docente. "
					+ "Tambien debe ingresar el curriculum, el titulo, el numero de documento y el CUIT/CUIL";
			throw new MissingArgumentException(mensaje);
		}
		
		try {
			this.getTeacherDAO().getByFileNumber(teacher.getFileNumber());
			throw new RepeatedInstanceException(
					"Ya existe o existio un docente con el legajo "
							+ teacher.getFileNumber());
		} catch (NoSuchEntityException e) {
			// si no encuentra el docente, se puede guardar (no existe ninguno con
			// ese legajo)
		}

		if (!teacher.getId().equals(toUpdateTeacher.getId())) {
			try {
				Teacher s = this.getById(teacher.getId());
				if (s.getId() != toUpdateTeacher.getId()) {
					throw new RepeatedNameException(
							"No se puede actualizar el docente. Ya hay otro docente en el sistema con el id "
									+ teacher.getId());
				}
			} catch (NoSuchEntityException e) {
				// significa que esta todo bien y puede actualizar la materia
				toUpdateTeacher.setName(teacher.getName());
				toUpdateTeacher.setFileNumber(teacher.getFileNumber());
				toUpdateTeacher.setBody(teacher.getBody());
				toUpdateTeacher.setValidFrom(teacher.getValidFrom());
				toUpdateTeacher.setValidTo(teacher.getValidTo());
				toUpdateTeacher.setCv(teacher.getCv());
				toUpdateTeacher.setDegree(teacher.getDegree());
				toUpdateTeacher.setPersonalId(teacher.getPersonalId());
				toUpdateTeacher.setTaxId(teacher.getTaxId());

				this.getTeacherDAO().update(toUpdateTeacher);
				teacher = toUpdateTeacher;
			}
		} else {
			toUpdateTeacher.setName(teacher.getName());
			toUpdateTeacher.setFileNumber(teacher.getFileNumber());
			toUpdateTeacher.setBody(teacher.getBody());
			toUpdateTeacher.setValidFrom(teacher.getValidFrom());
			toUpdateTeacher.setValidTo(teacher.getValidTo());
			toUpdateTeacher.setCv(teacher.getCv());
			toUpdateTeacher.setDegree(teacher.getDegree());
			toUpdateTeacher.setPersonalId(teacher.getPersonalId());
			toUpdateTeacher.setTaxId(teacher.getTaxId());

			this.getTeacherDAO().update(toUpdateTeacher);
			teacher = toUpdateTeacher;
		}
		return teacher;
	}

	/**
	 * @see ar.uba.fi.posgrado.academy.service.TeacherService#getByName(java.lang.String)
	 */
	@Transactional(readOnly = true)
	public List<Teacher> getByName(String name) throws PosgradoException {
		List<Teacher> response = null;
		try {
			CriterionBuilder builder = new CriterionBuilder();
			builder.add("name", name, ExpressionOperator.ILike);
			response = this.getTeacherDAO().findByCriterions(
					builder.toCriterions());

			if (logger.isDebugEnabled()) {
				logger.debug("# docentes con nombre " + name + " = "
						+ response.size());
			}
		} catch (DAOException e) {
			throw new PosgradoException(
					"Excepcion buscando docentes con criterios", e);
		}

		return response;
	}

	public List<Teacher> getAllValid() throws PosgradoException {
		return this.getTeacherDAO().findAllValid();
	}

	/**
	 * @see ar.uba.fi.posgrado.common.service.GenericService#filter(java.util.List,
	 *      ar.uba.fi.posgrado.common.model.User)
	 */
	public List<Teacher> filter(List<Teacher> list, User user)
			throws PosgradoRuntimeException, PosgradoException {
		if (!user.hasBodyRole()) {
			return list;
		}
		final Body body = user.getBody();
		if (logger.isDebugEnabled()) {
			logger
					.debug("El usuario tiene el rol Ente. Filtrando la docentes para el "
							+ "ente: " + body);
		}

		CollectionUtils.filter(list, new Predicate() {
			public boolean evaluate(Object object) {
				Teacher teacher = (Teacher) object;
				if (teacher.getBody().equals(body)) {
					return true;
				}

				return false;
			}
		});

		return list;
	}

}
